package com.hzit.auth.config;

import com.hzit.auth.filter.HzitAuthenticationFilter;
import com.hzit.auth.handler.HzitAccessDeniedHandler;
import com.hzit.auth.handler.HzitAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 类名：
 * 作者：WF
 * 功能：SpringSecurity配置类
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class HzitAuthConfig {
	@Autowired
	private HzitAuthenticationEntryPoint authenticationEntryPoint;
	@Autowired
	private HzitAccessDeniedHandler accessDeniedHandler;
	@Autowired
	private HzitAuthenticationFilter hzitAuthenticationFilter;
	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		//1. 处理认证和授权异常
		http.csrf().disable()
				.exceptionHandling()
				.authenticationEntryPoint(authenticationEntryPoint)
				.accessDeniedHandler(accessDeniedHandler);
		//2. 因为我们使用的是token机制，所以，这里取消默认的session存储机制
		http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

		//3. 处理放行页面及其它请求需要认证才能访问
		http.authorizeRequests()
				.anyRequest().authenticated();

		//4. 认证处理逻辑
		http.addFilterBefore(hzitAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
		return http.build();
	}

	@Bean
	public WebSecurityCustomizer webSecurityCustomizer() {
		return (web) -> web.ignoring().antMatchers("/webjars/**","/user/login");
	}
	// 密码加密器
	@Bean
	public PasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
	}

	@Bean
	public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
		return configuration.getAuthenticationManager();
	}
}
